var wgtVer=null;
function plusReady(){
    plus.runtime.getProperty(plus.runtime.appid,function(inf){
        wgtVer=inf.version;
    });
	
	// 检测更新
	var checkUrl = UrlConfig.auto_update;
	function checkUpdate(){
	    $.ajax(checkUrl, {  
		        data : {},  
		        dataType : 'jsonp',  
		        crossDomain: true,  
		        success: function(data) {
		        		data = JSON.parse(data);
		        		var success = data.success;
		        		var msg = data.msg;
		        		if(!success){
		        			mui.alert(msg);
		        		}else{
		        			installPackage(data);
		        		}
		        }
		    });
	}
	checkUpdate();
	/**
	 * 检查APP版本是否能更新 
	 * @param {Object} version
	 */
	function checkVersion(version){
		var old_arr = wgtVer.split(".");
		var old_totalVersion = getTotalVersion(old_arr);
		var new_arr = version.split(".");
		var new_totalVersion = getTotalVersion(new_arr);
		var isUpdate = (new_totalVersion > old_totalVersion);
		return isUpdate;
	}
	
	function getTotalVersion(arr){
		var num = "1";
		var total_v = 0;
		for(var i=arr.length-1; i>=0; i--){
			var v = arr[i];
			var c_num = parseInt(num);
			v = parseInt(v) * c_num;
			total_v += v;
			num+="0";
		}
		return total_v;
	}
	
	/**
	 * 安装升级包 
	 * @param {Object} data
	 */
	function installPackage(data){
		var version = data.version;
		if(!wgtVer){
			mui.alert("未检查到当前App版本，无法进行更新检查!");
			return;
		}
		if(!checkVersion(version)) return;
		//if(version == wgtVer) return;
		/*-------- 开始更新下载 -------*/
		var downLoadUrl = data.fileName;
		var remark = data.remark;
		if(!remark){
			remark = "确定更新应用程序吗?";	
		}else{
			remark = remark.replaceAll("<br/>","\n");
		}
		mui.confirm( remark,"软件版本更新", ["立即更新","退出应用"] , function(e){
			var index = e.index;
			if(index == 0){
				downWgt(data);		
			}else{/*退出APP应用*/
				 plus.runtime.quit();
			}
		});
	}
	
	var mask = mui.createMask(function(){});//callback为用户点击蒙版时自动执行的回调；

	// 下载wgt文件
	//var wgtUrl="http://demo.dcloud.net.cn/test/update/H5EF3C469.wgt";
	function downWgt(data){
		var wgtUrl = UrlConfig.download_update;
		mask.show();//显示遮罩
	    plus.nativeUI.showWaiting("正在下载更新文件...");
	    plus.downloader.createDownload( wgtUrl, {filename:"_doc/update/"}, function(d,status){
	        if ( status == 200 ) { 
	            console.log("下载wgt成功："+d.filename);
	            installWgt(d.filename); // 安装wgt包
	        } else {
	            console.log("下载wgt失败！");
	            plus.nativeUI.alert("下载更新文件失败！");
	            plus.nativeUI.closeWaiting();
	            mask.close();
	        }
	    }).start();
	}
	
	// 更新应用资源
	function installWgt(path){
		mask.show();//显示遮罩
	    plus.nativeUI.showWaiting("正在安装更新文件...");
	    plus.runtime.install(path,{},function(){
	        plus.nativeUI.closeWaiting();
	        mask.close();
	        console.log("安装更新文件成功！");
	        plus.nativeUI.alert("应用资源更新完成！",function(){
	            plus.runtime.restart();
	        });
	    },function(e){
	        plus.nativeUI.closeWaiting();
	        mask.close();
	        console.log("安装更新文件失败["+e.code+"]："+e.message);
	        plus.nativeUI.alert("安装更新文件失败["+e.code+"]："+e.message);
	    });
	}
}

if(window.plus){
    plusReady();
}else{
    document.addEventListener('plusready',plusReady,false);
}